package com.huijutao.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huijutao.MyApp;
import com.huijutao.NetUrl;
import com.huijutao.R;
import com.huijutao.adapter.HcYouhuiAdapter;
import com.huijutao.beans.HcYouHui;
import com.huijutao.callback.ABSFragment;
import com.huijutao.callback.StringDataCallBack;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FMHaiTao.HaiFragmentCallBack} interface
 * to handle interaction events.
 * Use the {@link FMHaiTao#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FMHaiTao extends ABSFragment implements AdapterView.OnItemClickListener, StringDataCallBack {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    // TODO: Rename and change types of parameters
    private String mParam1;
    private HaiFragmentCallBack mListener;
    private int page=1,r=0;
    private ArrayList<HcYouHui> datas;
    private HcYouhuiAdapter adapter;
    private PullToRefreshListView refreshListView;

    public static FMHaiTao newInstance(String param1) {
        FMHaiTao fragment = new FMHaiTao();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    public FMHaiTao() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }
    }
    @Override
    public void setType(int r) {
        this.r=r;
        datas.clear();
        MyApp.mStringUtils.getDataJson(NetUrl.getYouhuiUrl(page=1,r),this);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v=inflater.inflate(R.layout.fragment_haitao, container, false);
        refreshListView = (PullToRefreshListView) v.findViewById(R.id.hai_list);
        ListView list = refreshListView.getRefreshableView();
        datas = new ArrayList<HcYouHui>();
        MyApp.mStringUtils.getDataJson(NetUrl.getHaihuiUrl(page,r), this);
        adapter = new HcYouhuiAdapter(getActivity(),datas);
        list.setAdapter(adapter);
        /**
         * PullToRefreshListView
         */
        refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        final ILoadingLayout iLoadingLayout = refreshListView.getLoadingLayoutProxy();
        iLoadingLayout.setPullLabel("正在加载....");
        iLoadingLayout.setReleaseLabel("放开刷新");
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                iLoadingLayout.setPullLabel("下拉刷新");
                String time = DateUtils.formatDateTime(getActivity(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL);
                iLoadingLayout.setLastUpdatedLabel(time);
                MyApp.mStringUtils.getDataJson(NetUrl.getHaihuiUrl(1,r), new StringDataCallBack() {
                    @Override
                    public void stringDataCallBack(String data) {
                        //重新下载
                        datas.clear();
                        hcDown(data);
                    }
                });
                Toast.makeText(getActivity(), "done", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                iLoadingLayout.setPullLabel("上拉加载");
                String time = DateUtils.formatDateTime(getActivity(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL);
                iLoadingLayout.setLastUpdatedLabel(time);
                MyApp.mStringUtils.getDataJson(NetUrl.getHaihuiUrl(++page,r), new StringDataCallBack() {
                    @Override
                    public void stringDataCallBack(String data) {
                        hcDown(data);
                    }
                });
            }
        });
        list.setOnItemClickListener(this);
        return v;
    }
    /**
     * 下载的数据，json解析
     *
     * @param data
     */
    @Override
    public void stringDataCallBack(String data) {

        hcDown(data);
    }
    public void hcDown(String data) {

        try {
            JSONObject jsob=new JSONObject(data);
            JSONArray jsonArray=jsob.getJSONArray("data");
            for (int i=0;i<jsonArray.length();i++){
                JSONObject jsob1=jsonArray.getJSONObject(i);
                String id=jsob1.getString("id");
                HcYouHui youhui=new HcYouHui();
                youhui.setTitle(jsob1.getString("title"));
                youhui.setSubtitle(jsob1.getString("subtitle"));
                youhui.setPraise(jsob1.getString("img_path480"));
                youhui.setContent(jsob1.getString("content"));
                youhui.setPraise(jsob1.getString("praise"));
                youhui.setImg_path(jsob1.getString("img_path"));
                youhui.setGo_websit(jsob1.getString("go_website"));
                youhui.setGo_url(jsob1.getString("go_url"));
                youhui.setTime(""+jsob1.getLong("time"));
                datas.add(youhui);
            }
            adapter.notifyDataSetChanged();
            refreshListView.onRefreshComplete();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        HcYouHui youhui;
        youhui=datas.get(position-1);
        mListener.haiFragmentCallBack(youhui.getImg_path(), youhui.getTitle(), youhui.getSubtitle(), youhui.getGo_websit(), youhui.getGo_url(), youhui.getPraise(), youhui.getContent());
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (HaiFragmentCallBack) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface HaiFragmentCallBack {
        // TODO: Update argument type and name
        public void haiFragmentCallBack(String img_path, String title, String subtitle, String go_websit, String go_url, String praise, String content);
    }

}
